#!/usr/bin/env python

import sys
import pyxmppxmpp as gxmpp
import pylock as glock
from pychatuser import ChatUser

import gootalk

def addUser(jid):
    id = jid.split('/')[0]
    if (id == gootalk.jid):
        return None
    glock.lock('User_Add')
    u = getUser(id)
    if (u == None):
        u = ChatUser(
                jid = id.lower(),
                nick = id.split('@')[0]
            )
        u.put()
    glock.unlock('User_Add')
    return u

def getUser(jid):
    id = jid.split('/')[0]
    u = ChatUser.getByJid(id.lower())
    return u 

def getUserByNick(nick):
    return ChatUser.getByNick(nick)

def getUsers(available=None):
    return ChatUser.all()

def inviteUser(jid, inviteby):
    glock.lock('User_Add')
    u = getUser(jid)
    if (u == None):
        id = jid.split('/')[0]
        u = ChatUser(
                jid = id.lower(),
                nick = id.split('@')[0],
                inviting = True,
                inviteby = inviteby
            )
        gxmpp.sendInvite(u.jid)
        u.put()
    glock.unlock('User_Add')
    return u

def setNick(jid, nick):
    u = addUser(jid)
    if (u):
        glock.lock('User_Mod_' + u.jid)
        u.nick = nick
        u.put()
        glock.unlock('User_Mod_' + u.jid)
    return u

def setAvailable(jid, available):
    u = addUser(jid)
    if (u):
        glock.lock('User_Mod_' + u.jid)
        u.available = available
        u.put()
        glock.unlock('User_Mod_' + u.jid)

def init():
    ChatUser.init()
